Posts = new Mongo.Collection('posts');

// Posts.allow({
//     //need userid for insert
//     insert: function (userId, doc) {
//         return !!userId;
//     }
// });


Posts.allow({
    update: function (userId, post) { return ownsDocument(userId, post); },
    remove: function (userId, post) { return ownsDocument(userId, post); }
});


Meteor.methods({
    postInsert: function (postAttributes) {
        //check the data's style
        check(Meteor.userId(), String);
        check(postAttributes, {
            title: String,
            url: String
        });

        //DPP TEST
        if (Meteor.isServer) {
            postAttributes.title += "(server)";
            // wait for 5 seconds
            Meteor._sleepForMs(5000);
        } else {
            postAttributes.title += "(client)";
        }


        //the samelink check
        var postWithSameLink = Posts.findOne({ url: postAttributes.url });
        if (postWithSameLink) {
            return {
                postExists: true,
                _id: postWithSameLink._id
            }
        }
        //The same title check
        var postWithSameTitle = Posts.findOne({ title: postAttributes.title });
        if (postWithSameTitle) {
            return {
                postExists: true,
                _id: postWithSameTitle._id
            }
        }

        var user = Meteor.user();
        var post = _.extend(postAttributes, {
            userId: user._id,
            author: user.username,
            submitted: new Date()
        });

        var postId = Posts.insert(post);

        return {
            _id: postId
        };

    }
});